'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#作者：cacho_37967865
#博客：https://blog.csdn.net/sinat_37967865
#文件：comtypes_model.py
#日期：2018-04-22
#备注：通过调用Python访问COM对象的comtypes包，批量将ppt或者word转换为PDF文件，先要在python环境安装comtypes       
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

from comtypes.client import CreateObject
import os

class pdfConverter:
    def __init__(self):
        #word文档转化为pdf文档时使用的格式为17
        self.wdFormatPDF = 17
        self.wdToPDF = CreateObject("Word.Application")
        #ppt文档转化为pdf文档时使用的格式为32
        self.pptFormatPDF = 32
        self.pptToPDF = CreateObject("Powerpoint.Application")
        #self.pptToPDF.Visible = 1     # 设为1会打开程序，默认设为0
        self.excelFormatPDF = 2
        self.excelToPDF = CreateObject("Excel.Application")



    def wd_to_pdf(self, folder):
        #获取指定目录下面的所有文件
        files = os.listdir(folder)
        #获取word类型的文件放到一个列表里面
        wdfiles = [f for f in files if f.endswith((".doc", ".docx"))]
        for wdfile in wdfiles:
            #将word文件放到指定的路径下面
            wdPath = os.path.join(folder, wdfile)
            #设置将要存放pdf文件的路径
            pdfPath = wdPath[:-4]
            #判断是否已经存在对应的pdf文件，如果不存在就加入到存放pdf的路径内
            if pdfPath[-3:] != 'pdf':
                pdfPath = pdfPath + ".pdf"
            #将word文档转化为pdf文件，先打开word所在路径文件，然后在处理后保存pdf文件，最后关闭
            pdfCreate = self.wdToPDF.Documents.Open(wdPath)
            pdfCreate.SaveAs(pdfPath, self.wdFormatPDF)
            pdfCreate.Close()

    def ppt_to_pdf(self, folder):
        files = os.listdir(folder)
        pptfiles = [f for f in files if f.endswith((".ppt", ".pptx"))]
        for pptfile in pptfiles:
            pptPath = os.path.join(folder, pptfile)
            pdfPath = pptPath[:-4]
            if pdfPath[-3:] != 'pdf':
                pdfPath = pdfPath + ".pdf"
            pdfCreate = self.pptToPDF.Presentations.Open(pptPath)
            pdfCreate.SaveAs(pdfPath, self.pptFormatPDF)
            pdfCreate.Close()


    def excel_to_pdf(self, folder):
        files = os.listdir(folder)
        excelfiles = [f for f in files if f.endswith((".xls", ".xlsx"))]
        for excelfile in excelfiles:
            excelPath = os.path.join(folder, excelfile)
            pdfPath = excelPath[:-4]
            if pdfPath[-3:] != 'pdf':
                pdfPath = pdfPath + ".pdf"
            pdfCreate = self.excelToPDF.Workbooks.Open(excelPath)
            pdfCreate.SaveAs(pdfPath, self.excelFormatPDF,None)
            pdfCreate.Close()

if __name__ == "__main__":
    converter = pdfConverter()
    folder = input('请输入想要转换的目录：\n')
    converter.ppt_to_pdf(folder)





